package com.grape.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 类描述： 字母大小写转换工具类
 *
 * @author  putao
 * @email   2628279194@qq.com
 */
public class HumpUtil {

    private final static Pattern UNDERLINE_PATTERN = Pattern.compile("_([a-z])");
    private final static Pattern LINE_PATTERN = Pattern.compile("_(\\w)");
    private final static Pattern HUMP_PATTERN = Pattern.compile("[A-Z]");

    /**
     * 根据传入的带下划线的字符串转化为驼峰格式
     * @param str   下划线的字符串
     * @return      驼峰式的字符串
     */
    public static String underlineToHump (String str){
        //正则匹配下划线及后一个字符，删除下划线并将匹配的字符转成大写
        Matcher matcher = UNDERLINE_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer(str);
        if (matcher.find()) {
            sb = new StringBuffer();
            //将当前匹配的子串替换成指定字符串，并且将替换后的子串及之前到上次匹配的子串之后的字符串添加到StringBuffer对象中
            //正则之前的字符和被替换的字符
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
            //把之后的字符串也添加到StringBuffer对象中
            matcher.appendTail(sb);
        } else {
            //去除除字母之外的前面带的下划线
            return sb.toString().replaceAll("_", "");
        }
        return underlineToHump(sb.toString());
    }

    /**
     * 下划线转驼峰
     * @param str   待转化的字符串
     * @return      驼峰式的字符串
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = LINE_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 驼峰转下划线
     * @param str       驼峰式字符串
     * @return          下划线字符串
     */
    public static String humpToLine(String str) {
        Matcher matcher = HUMP_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 驼峰转
     * @param str   待转字符串
     * @param rule  转换规则
     * @return      转换后字符串
     */
    public static String ruleHump(String str, String rule) {
        Matcher matcher = HUMP_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, rule + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

}
